package eva

import (
	"context"

	"trusteva/app/eva/internal/ruleutil"
	"trusteva/app/eva/internal/svc"
	"trusteva/app/eva/internal/types"
	"trusteva/app/eva/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddRulesLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddRulesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddRulesLogic {
	return &AddRulesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddRulesLogic) AddRules(req *types.AddRulesRo) (resp *types.AddRulesRsp, err error) {
	// todo: add your logic here and delete this line
	for _, rule := range req.Rules {
		rule := model.Rule{
			AppId:    rule.AppId,
			DeviceId: rule.DeviceId,
			DstIP:    rule.DstIP,
			DstPort:  rule.DstPort,
			Status:   rule.Status,
		}
		rules, err := ruleutil.ParseRules(rule)
		if err != nil {
			return nil, err
		}

		err = l.svcCtx.DB.WithContext(l.ctx).Create(&rule).Error
		if err != nil {
			return nil, err
		}

		if rule.Status == model.RulePass {
			for _, v := range rules {
				_, err = l.svcCtx.RedisClient.SaddCtx(l.ctx, model.RuleSetKey, v.Key())
				if err != nil {
					logx.Error("SaddCtx", v.Key(), err)
					return nil, err
				}
			}
		}
		// resp.Rules[rid] = rule
	}

	return
}
